package logic

import (
	"context"

	"googee/common/tool"
	"googee/service/sms/rpc/internal/svc"
	"googee/service/sms/rpc/types/sms"

	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type VerifyCodeLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewVerifyCodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *VerifyCodeLogic {
	return &VerifyCodeLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

//  验证类短信验证
func (l *VerifyCodeLogic) VerifyCode(in *sms.VerifyRequest) (*sms.VerifyResponse, error) {
	phone := in.GetPhone()
	userId := in.GetId()
	code := in.GetCode()

	if phone == "" || !tool.VerifyMobileFormat(phone) {
		return nil, status.Error(codes.InvalidArgument, "parameter password is empty or phone is not a valid phone number")
	}

	if code == "" {
		return nil, status.Error(codes.InvalidArgument, "parameter password is empty or phone is not a valid phone number")
	}

	//检查code是否争取
	codesms, _ := l.svcCtx.SmsModel.FindOneVerifySmsByUserId(l.ctx, userId, code, l.svcCtx.Config.VerifySMS.Valid)
	if codesms == nil {
		return nil, status.Error(codes.NotFound, "not found valid code short message")
	}

	if codesms.Content.String != code {
		return &sms.VerifyResponse{Code: 1}, nil
	}

	codesms.Valid = 0
	l.svcCtx.SmsModel.Update(l.ctx, codesms)

	return &sms.VerifyResponse{}, nil
}
